<?php

namespace app\api\controller;

use app\admin\model\money\Change;
use app\admin\model\product\Category;
use app\admin\model\product\Listo;
use app\admin\model\product\Lists;
use app\admin\model\product\Order;
use app\admin\model\product\Sku;
use app\admin\model\product\Value;
use app\admin\model\user\Finance;
use app\common\api\controller\Relation;
use app\common\model\Member;
use app\common\model\MemberFinance;
use think\Db;
use think\Request;
use app\common\controller\Api;
use think\Validate;

class Moneychange extends Api
{
    protected static $model = null;
    protected $noNeedRight = '*';

    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        self::$model = new Change();
    }


    public function create($data)
    {
        if (!request()->isPost()) {
            $this->error('非法操作！');
        }
        $user_id = $this->auth->id;
        $finance = Finance::where('user_id', $user_id)->find();
        $is_trans = input('is_trans', 1); //是否需要物流
        $tag = input('tag');
        $message = input('message');
        if (!$tag) {
            $this->error('非法操作！');
        }

//        $password = input('password');
//        if ($uinfo['psd2'] != $password) {
//            $this->apiError('支付密码错误！');
//        }

        $orderInfo = Order::where('orderid', $tag)->find();
        if ($orderInfo) {
            $this->error('重复提交订单');
        }

        $addressid = \app\admin\model\Transport::where("status='1' and user_id='$user_id'")->value('id');
        if ($addressid <= 0) {
            $this->error('必须默认一个收货地址！');
        }

        //获取该用户购物清单中的数据
        $shoplist = Listo::where('tag', $tag)->select();

        if (!$shoplist) {
            $this->error('请先购买商品！');
        }

        $nums = 0;
        $total = 0;
        $transfee = 0;
        $needMoney = 0;
        $needStock = 0;
        $mark = '';
        foreach ($shoplist as $v) {
            $productInfo = Lists::where('id', $v->product_id)->find();
            $cmark = Category::where('id', $productInfo->category_id)->value('mark');

            if ($mark == '') {
                $mark = $cmark;
            } else {
                if ($cmark != $mark) {
                    $this->error('一次只能购买一个种类的商品！');
                }
            }

            if ($cmark == 'bill' && $finance->hasscore > 0) {
                $this->error('积分余额尚未耗尽，不可购买报单产品！');
            }

            $nums += $v['num'];
            $total += $v['total'];
            if ($is_trans == 1) {
                $transfee += $productInfo['transfee'] * $v['num'];
            }
        }

        $all = $total + $transfee;

        if ($mark == 'bill') {
            // 报单
            if ($all > $finance->hasbill) {
                $this->error('账户报单积分余额不足，无法购买！');
            }
            $paytype = 1;
        } else {
            // 复消
            if ($all > $finance->hasshop) {
                $this->error('账户商城钱包余额不足，无法购买！');
            }
            $paytype = 6;
        }

        $data['addressid'] = $addressid;//收货人地址
        $data['total'] = $total;//总金额
        $data['transfee'] = $transfee;
        $data['all'] = $all;
        $data['orderid'] = $tag;//订单号
        $data['uid'] = $user_id;//当前用户id
        $data['backinfo'] = '预下单';
        $data['message'] = $message;
        $data['paytype'] = $paytype;//等待发货
        $data['mark'] = $mark;
        $data['status'] = 0;

        Db::startTrans();
        try {
            $odata = self::$model->create($data);
            Listo::where('tag', $tag)->setField('orderid', $odata->id);
            if ($mark == 'bill') {
                // 报单
                $finance->hasbill -= $all;
            } else {
                // 复消
                $finance->hasshop -= $all;
            }

            $finance->save();

            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->error($e->getMessage());
        }

        if ($mark == 'bill') {
            $type = array('recordtype' => 0, 'changetype' => 26, 'moneytype' => 1);
            $money = array('money' => $needStock, 'hasmoney' => $memberFinanceModel->hasbill);
            money_change($type, $uid, 0, $money, $tag);
            unset($type, $money);
        } else {
            $type = array('recordtype' => 0, 'changetype' => 26, 'moneytype' => 3);
            $money = array('money' => $needStock, 'hasmoney' => $memberFinanceModel->hascp);
            money_change($type, $uid, 0, $money, $tag);
            unset($type, $money);
        }

        $type = array('recordtype' => 0, 'changetype' => 26, 'moneytype' => 2);
        $money = array('money' => $needMoney, 'hasmoney' => $memberFinanceModel->hasmoney);
        money_change($type, $uid, 0, $money, $tag);
        unset($type, $money);

        if ($uinfo['userrank'] == 0) {
            (new Relation())->getPosition($uid);
        }

        $bonus = new Bonus($uid, $needStock, $mark);
        if ($uinfo['userrank'] <= 0) {
            // 先发奖后升级
            $bonus->bonusRecom();
            $bonus->bonusPoint1();
            $bonus->bonusStore();
            $bonus->bonusUpdate();
        } elseif ($uinfo['userrank'] == 1) {
            // 先发奖后升级
            if ($mark == 'bill') {
                $bonus->bonusRecom();
                $bonus->bonusPoint1();
                $bonus->bonusStore();
                $bonus->bonusUpdate();
            } elseif ($mark == 'cp') {
                $bonus->bonusPoint2();
            }
        } else {
            $bonus->bonusPoint2();
        }

        $bonus->addAchievement();
        /*更新状态*/
        $ndata = [
            'pay_time' => time(),
            'status' => 1
        ];
        Db('shop_order')->where('id', $order_id)->update($ndata);
        Db('shoplist')->where('orderid', $order_id)->update($ndata);

        finance1($needStock);

        /*公司发货更新商品销量*/
        $shoplists = Db('shoplist')->where('tag', $tag)->select();
        self::updateShop($shoplists);

        $this->apiSuccess("订单提交成功！");

    }
}